
package com.wolfheader.wolfgame.service.impl;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.wolfheader.wolfgame.entity.admin.AdminEntity;
import com.wolfheader.wolfgame.service.RsaService;
import com.wolfheader.wolfgame.util.RSAUtils;

/**
 * Service - RSA安全
 * 
 * @author 8615 Team
 * @version 1.0
 */
@Service("myRsaServiceImpl")
public class RsaServiceImpl implements RsaService {

    @Override
    public RSAPublicKey generateKey(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        // 已存在密钥
        HttpSession session = request.getSession();
        KeyPair sKeyPair = (KeyPair) session.getAttribute(AdminEntity.KEY_ATTR);
        if (sKeyPair != null) {
            return (RSAPublicKey) sKeyPair.getPublic();
        }
        // 生成密钥
        KeyPair keyPair = RSAUtils.generateKeyPair();
        session.setAttribute(AdminEntity.KEY_ATTR, keyPair);
        return (RSAPublicKey) keyPair.getPublic();
    }

    @Override
    public void removePrivateKey(HttpServletRequest request) {
        if (request == null) {
            return;
        }
        HttpSession session = request.getSession();
        session.removeAttribute(AdminEntity.KEY_ATTR);
    }

    @Override
    public String decryptParameter(String name, HttpServletRequest request) {
        if (StringUtils.isBlank(name) || request == null) {
            return null;
        }
        String parameter = request.getParameter(name);
        HttpSession session = request.getSession();
        KeyPair sKeyPair = (KeyPair) session.getAttribute(AdminEntity.KEY_ATTR);
        if (StringUtils.isBlank(parameter) || sKeyPair == null) {
            return null;
        }
        RSAPrivateKey privateKey = (RSAPrivateKey) sKeyPair.getPrivate();
        return RSAUtils.decrypt(privateKey, parameter);
    }

}